import dayjs from 'dayjs';

// 用户年龄转换
export const getAge = (strBirthday: string) => {
    let returnAge = '';
    let mouthAge = '';
    if (!strBirthday) {
        return returnAge = '45';
    }
    const strBirthdayArr = strBirthday.split("-");
    const birthYear = parseInt(strBirthdayArr[0], 10);
    const birthMonth = parseInt(strBirthdayArr[1], 10);
    const birthDay = parseInt(strBirthdayArr[2], 10);
    const d = new Date();
    const nowYear = d.getFullYear();
    const nowMonth = d.getMonth() + 1;
    const nowDay = d.getDate();
    if (nowYear == birthYear) {
        const monthDiff = nowMonth - birthMonth;
        if (monthDiff >= 0) {
            mouthAge = monthDiff.toString(); // 转换为字符串
        }
    } else {
        const ageDiff = nowYear - birthYear;
        if (ageDiff > 0) {
            if (nowMonth == birthMonth) {
                const dayDiff = nowDay - birthDay;
                if (dayDiff < 0) {
                    returnAge = (ageDiff - 1).toString();
                } else {
                    returnAge = ageDiff.toString();
                }
            } else {
                const monthDiff = nowMonth - birthMonth;
                if (monthDiff < 0) {
                    returnAge = (ageDiff - 1).toString();
                } else {
                    mouthAge = monthDiff.toString();
                    returnAge = ageDiff.toString();
                }
            }
        } else {
            returnAge = '-1';
        }
    }

    return returnAge;
};

// 时间戳=>时分秒
export function formatTime(timeStamp) {
    const date = new Date(timeStamp);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);
    return `${minutes}:${seconds}`;
}

// 数字时间戳转为时分秒
export function formatTimestamp(timestamp, type = 0) {
    // 将时间戳转换为毫秒
    const milliseconds = timestamp * 1000;
    // 创建一个Date对象
    const dateObject = new Date(milliseconds);
    // 获取年、月、日
    const year = dateObject.getFullYear();
    const month = String(dateObject.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始，所以要加1
    const day = String(dateObject.getDate()).padStart(2, '0');
    // 获取小时、分钟和秒
    const hours = dateObject.getHours();
    const minutes = dateObject.getMinutes();
    const seconds = dateObject.getSeconds();

    // 将单个数字的小时、分钟和秒转换为两位数格式（例如：9 => 09）
    const formattedHours = String(hours).padStart(2, '0');
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(seconds).padStart(2, '0');
    // 返回格式化后的时间字符串

    return type == 0 ? `${year}/${month}/${day}` : type == 1 ? `${year}/${month}/${day} ${formattedHours}:${formattedMinutes}:${formattedSeconds}` : `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}


export function formatTimeToHoursMinutes(utcTimeString, timezoneOffset = 0) {
    const date = new Date(utcTimeString);
    // 计算指定时区的小时和分钟
    const hours = (date.getUTCHours() + timezoneOffset) % 24;
    const minutes = date.getUTCMinutes();
    const adjustedHours = hours < 0 ? hours + 24 : hours;
    // 格式化输出为 "小时:分钟"
    return `${adjustedHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
}


// 将数字改为周几
export function changWeekArr(str) {
    const valuesArray = str.split(',');
    const dayMapping = {
        '1': '周一',
        '2': '周二',
        '3': '周三',
        '4': '周四',
        '5': '周五',
        '6': '周六',
        '7': '周日'
    };
    const chineseDaysArray = valuesArray.map(value => dayMapping[value]);
    const chineseDaysString = chineseDaysArray.join(',');
    return chineseDaysString
}


// 获取当前时间
export function getCurrentDate(type = 0) {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
    const day = String(date.getDate()).padStart(2, '0');
    // 获取小时、分钟和秒
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    // 将单个数字的小时、分钟和秒转换为两位数格式（例如：9 => 09）
    const formattedHours = String(hours).padStart(2, '0');
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(seconds).padStart(2, '0');

    return type == 1 ? `${year}-${month}-${day} ${formattedHours}:${formattedMinutes}:${formattedSeconds}` : `${year}-${month}-${day}`;
}


// 根据某月一天放回当前月的第一天跟最后一天
export function getFirstAndLastDayOfMonth(yearMonth) {
    const [year, month] = yearMonth.split('-').map(Number);
    const firstDay = new Date(year, month - 1, 1);
    const lastDay = new Date(year, month, 0);  // 设置为下个月的第0天，得到当前月的最后一天
    const formatDate = (date) => {
        const yyyy = date.getFullYear();
        const mm = String(date.getMonth() + 1).padStart(2, '0');
        const dd = String(date.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
    };
    return {
        firstDay: formatDate(firstDay),
        lastDay: formatDate(lastDay)
    };
}

export function getMonthStartAndEnd(date = new Date()) {
    const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
    const formatDate = (d) => {
        const year = d.getFullYear(); // 获取后两位年份
        const month = String(d.getMonth() + 1).padStart(2, '0'); // 补零到两位
        const day = String(d.getDate()).padStart(2, '0'); // 补零到两位
        return `${year}-${month}-${day}`;
    };
    return {
        firstDay: formatDate(firstDay),
        lastDay: formatDate(lastDay)
    };
}

// 获取本周第一天跟最后一天
export function getWeekStartAndEnd(date = new Date()) {
    const today = dayjs(); // 当前日期
    const startOfWeek = today.startOf('week'); // 本周的开始日期（默认是周日，如果需要改成周一，可配置 day.js 插件）
    const endOfWeek = today.endOf('week'); // 本周的结束日期
    // 获取当前月份的开始和结束日期
    const startOfMonth = today.startOf('month');
    const endOfMonth = today.endOf('month');
    // 计算本周的实际开始日期，确保不会早于本月的开始日期
    const weekStart = startOfWeek.isBefore(startOfMonth) ? startOfMonth : startOfWeek;
    // 计算本周的实际结束日期，确保不会晚于本月的结束日期
    const weekEnd = endOfWeek.isAfter(endOfMonth) ? endOfMonth : endOfWeek;
    // 返回一个包含本周范围的对象
    return {
        weekStart: weekStart.format('YYYY-MM-DD'),
        weekEnd: weekEnd.format('YYYY-MM-DD')
    };


}

export function getNewDay(days) {
    let nd: any = new Date();
    nd = nd.valueOf();
    nd = nd + days * 24 * 60 * 60 * 1000;
    nd = new Date(nd);
    let y = nd.getFullYear();
    let m = nd.getMonth() + 1;
    //获取当前天
    let d = nd.getDate();
    if (m <= 9) m = "0" + m;
    if (d <= 9) d = "0" + d;
    let cdate = y + "-" + m + "-" + d;
    return cdate;
}



// 获取当前月的周
export const getCurrentMonthWeeks = () => {
    const firstDay = dayjs().startOf("month"); // 本月的第一天
    const lastDay = dayjs().endOf("month");   // 本月的最后一天
    const weeks: any = [];
    let currentDay = firstDay;

    while (currentDay.isBefore(lastDay) || currentDay.isSame(lastDay)) {
        const startOfWeek = currentDay.startOf("week"); // 当前周的周日
        const endOfWeek = currentDay.endOf("week");     // 当前周的周六

        const startTime = startOfWeek.isBefore(firstDay) ? firstDay : startOfWeek;
        const endTime = endOfWeek.isAfter(lastDay) ? lastDay : endOfWeek;
        const monday = startOfWeek.add(1, 'day'); // 当前周的周一
        weeks.push({
            startTime: startTime.format("YYYY-MM-DD"),
            endTime: endTime.format("YYYY-MM-DD"),
            monday: monday.format("YYYY-MM-DD"),
        });
        currentDay = currentDay.add(1, "week").startOf("week");
    }

    return weeks;
};

// 获取当前周
export const getCurrentWeekInfo = () => {
    const today = dayjs(); // 获取今天日期

    const startOfWeek = today.startOf("week"); // 当前周的周日
    const endOfWeek = today.endOf("week");     // 当前周的周六
    const monday = startOfWeek.add(1, "day");  // 当前周的周一

    return {
        startTime: startOfWeek.format("YYYY-MM-DD"), // 周日
        endTime: endOfWeek.format("YYYY-MM-DD"),     // 周六
        monday: monday.format("YYYY-MM-DD"),         // 周一
    };
};